﻿var OrdersPending = function () {
    var settings = {
        getOrders: "/OrdersManagment/Orders/GetOrders/",
        PrepareOrder: "/OrdersManagment/Orders/PrepareOrder/",
        FinishOrder: "/OrdersManagment/Orders/FinishOrder/",
        OrderTaken: "/OrdersManagment/Orders/OrderTaken/"
    };

    var _getOrdersDataFunc;
    this.Init = function (opts) {
        settings =
            $.extend(
                settings,
                opts);

        var employeeSelectDlg = $("#employeeSelectDlg");
        employeeSelectDlg.dialog({ autoOpen: false });

        _getOrdersDataFunc = this.getOrdersData;
        employeeSelectDlg.find("form").submit(function () {
            // Maybe show a loading indicator...
            $.post(this.action, $(this).serialize(), function (res) {
                // Do something with the response `res`
                // Don't forget to hide the loading indicator!

                employeeSelectDlg.dialog("close");
                _getOrdersDataFunc();
            });

            return false; // prevent default action
        });

        this.getOrdersData();
    };

    this.getOrdersData = function () {
        $.ajax({
            url: settings.getOrders,
            type: "post"
        }).done(function (lists) {
            fillList($("#OrdersPendingList"), lists.PendingOrders, function () {
                $("#employeeSelectDlg").find("#orderId").val($(this).data("id"));
                $("#employeeSelectDlg").dialog("open");
            });

            fillList($("#OrdersOnPrepList"), lists.OnPrepOrders, function () {
                $.ajax({
                    url: settings.FinishOrder,
                    type: "post",
                    data: { orderId: $(this).data("id") }
                }).done(function (items) {
                    _getOrdersDataFunc();
                });
            });

            fillList($("#OrdersFinishedList"), lists.FinishedOrders, function () {
                $.ajax({
                    url: settings.OrderTaken,
                    type: "post",
                    data: { orderId: $(this).data("id") }
                }).done(function (items) {
                    _getOrdersDataFunc();
                })
            });
        });
    };

    function fillList(container, list, clickFunc) {
        container.html("");
        for (var itm in list) {
            var li = createItem(list[itm]);

            if (clickFunc) {
                li.click(clickFunc);
            }

            container.append(li);
        }
    }

    function createItem(item) {
        return $("<li data-id=" + item.orderId + ">" + item.orderId + " (" + item.count + ") " + item.date + "</li>");
    }
}